package p.ithorns.integration.crypto;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.*;
import p.ithorns.framework.crypto.annotation.Decrypt;
import p.ithorns.framework.crypto.annotation.EnableCrypto;
import p.ithorns.framework.crypto.annotation.Encrypt;
import p.ithorns.framework.crypto.core.CryptoProperties;

import java.util.Map;

/**
 * @author ithorns
 */
@Slf4j
@EnableCrypto
@RestController
@EnableAspectJAutoProxy
@SpringBootApplication
public class CryptoApplication implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        CryptoApplication.context = context;
    }

    public static void main(String[] args) {
        SpringApplication.run(CryptoApplication.class, args);

        CryptoProperties bean = CryptoApplication.context.getBean(CryptoProperties.class);
        System.out.println(bean);
    }


    @GetMapping("/getPrivateKey")
    public String getPrivateKey() throws Exception {
        Map<String, Object> keys = RSAUtils.genKeyPair();
        String pri = RSAUtils.getPrivateKey(keys);
        String pub = RSAUtils.getPublicKey(keys);
        log.info("公钥==========>{}", pub);
        log.info("私钥==========>{}", pri);
        return pub;
    }

    @Decrypt
    @PostMapping("/req")
    public User req(@RequestBody User user) {
        log.info("返回解密内容=======>{}", user.toString());
        return user;
    }

    @Encrypt
    @PostMapping("/resp")
    public User resp(@RequestBody User user) {
        log.info("加密响应内容==========>{}", user.toString());
        return user;
    }


    @PostMapping("/test")
    public String test(@RequestParam("id") String id, @RequestParam("password") String password) {
        return id + ": " + password;
    }

    @PostMapping("/test2")
    public String test2(@RequestBody Map<String, Object> params) {
        String id = (String) params.get("id");
        String password = (String) params.get("password");
        return id + ": " + password;
    }

}
